﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Web.Syndication;

namespace RssReader
{
    public class LocalStorage
    {
        readonly StorageFolder _localFolder = ApplicationData.Current.LocalFolder;
        private const string SyndicationfeedFileName = "SyndicationFeed.txt";

        public async void Write_feed_to_disk(SyndicationFeed syndicationFeed)
        {
            StorageFile syndicationXml = await _localFolder.CreateFileAsync(SyndicationfeedFileName, CreationCollisionOption.ReplaceExisting);
            await FileIO.WriteTextAsync(syndicationXml, syndicationFeed.GetXmlDocument(syndicationFeed.SourceFormat).GetXml());
        }

        public async Task<SyndicationFeed> Read_feed_from_disk()
        {
            try
            {
                var syndicationFeedFile = await _localFolder.GetFileAsync(SyndicationfeedFileName);
                var syndicationFeedText = await FileIO.ReadTextAsync(syndicationFeedFile);
                var syndicationFeed = new SyndicationFeed();
                syndicationFeed.Load(syndicationFeedText);

                return syndicationFeed;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async void Delete_file_from_disk()
        {
            try
            {
                var syndicationFeedFile = await _localFolder.GetFileAsync(SyndicationfeedFileName);
                await syndicationFeedFile.DeleteAsync();
            }
            catch
            {
                // ToDo
            }

        }
    }
}
